package czx.wt;

import czx.wt.util.validcode.ValidateCodeFilter;
import czx.wt.web.security.MyAuthenticationFailureHandler;
import czx.wt.web.security.MyAuthenticationSuccessHandler;
import czx.wt.web.security.MyPasswordEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Description: 类作用描述
 * @Author: ChenZhiXiang
 * @CreateDate: 2018/12/20 0020 10:07
 * @Version: 1.0
 */
@Configuration
public class MySecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(MySecurityConfiguration.class);

    @Bean(name = "passwordEncoder")
    public PasswordEncoder passwordEncoder(){
        return new MyPasswordEncoder();
    }

    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .addFilterBefore(new ValidateCodeFilter(),UsernamePasswordAuthenticationFilter.class)
                .formLogin()
                .loginPage("/auth/require")  //需要认证跳转的地址
                .loginProcessingUrl("/login/login")  //登录页面请求地址
                .successHandler(myAuthenticationSuccessHandler)
                .failureHandler(myAuthenticationFailureHandler)
                .and()
                .authorizeRequests()
                .antMatchers("/auth/require","/error/unAuth.html","/login.html","/logout","/valid/code").permitAll()
                .anyRequest()
                .authenticated()
                .and().csrf().disable();
    }
}
